from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from new_login import models, serializers
from rest_framework.pagination import PageNumberPagination

# Create your views here.

class New_login(ModelViewSet):
    queryset = models.New_login.objects.all()
    serializer_class = serializers.LoginSerializer

    @action(detail=False, methods=["post"])
    def login(self, request):
        name = request.data.get("name")
        password = request.data.get("password")
        data = models.New_login.objects.filter(name=name)
        if data:
            data = models.New_login.objects.filter(name=name, password=password)
            if data:
                return Response({"msg": "ok"})
            else:
                return Response({"msg": "password is wrong"})
        else:
            return Response({"msg": "name is wrong"})

    @action(detail=False, methods=["post"])
    def register(self, request):
        name = request.data.get("name")
        data = models.New_login.objects.filter(name=name)
        if data:
            return Response({"msg": "name already exist"})
        else:
            password = request.data.get("password")
            if password:
                models.New_login.objects.create(
                    name=name,
                    password=password
                )
                return Response({"msg": "ok"})
            else:
                return Response({"msg": "password can't empty"})

class MyPage(PageNumberPagination):
    page_size = 3
    page_size_query_param = "size"

class My_goods(ModelViewSet):
    queryset = models.My_goods.objects.all()
    serializer_class = serializers.My_goodsSerializer
    pagination_class = MyPage

